package com.heima.user.interceptor;

import com.heima.utils.thread.AppUserThreadLocalUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取 userId
        String userId = request.getHeader("userId");
        //存入ThreadLocal
        if (StringUtils.isNotBlank(userId)) {
            AppUserThreadLocalUnit.set(Integer.parseInt(userId));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理数据
        AppUserThreadLocalUnit.clear();
    }
}
